package cn.com.huzo.service.purchase.impl;

import cn.com.huzo.model.entities.purchase.PoHeaderEntity;
import huzofw.model.entities.paginator.Paginator;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.service.purchase.PoHeaderManager;
import cn.com.huzo.service.purchase.PoLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpLinesManager;
import cn.com.huzo.service.purchase.PoLinesMrpFeedingLinesManager;
import cn.com.huzo.repository.purchase.PoHeaderRepository;
import cn.com.huzo.repository.purchase.PoLinesRepository;
import cn.com.huzo.repository.purchase.PoLinesMrpFeedingRepository;
import cn.com.huzo.repository.purchase.PoLinesMrpLinesRepository;
import cn.com.huzo.repository.purchase.PoLinesMrpRepository;
import cn.com.huzo.repository.tech.MrpLinesResultRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesRepository;

/**
 * 采购订单管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("PoHeaderManager")
public class PoHeaderManagerImpl extends GenericManagerImpl<PoHeaderEntity, Long>
        implements PoHeaderManager {

    @Resource(name = "PoHeaderRepository")
    private PoHeaderRepository _dao;

    @Resource(name = "PoLinesMrpRepository")
    private PoLinesMrpRepository _dao_lines_mrp;

    @Resource(name = "PoLinesMrpLinesRepository")
    private PoLinesMrpLinesRepository _dao_lines_mrp_lines;

    @Resource(name = "PoLinesMrpFeedingRepository")
    private PoLinesMrpFeedingRepository _dao_lines_mrp_feeding;

    @Resource(name = "PoLinesRepository")
    private PoLinesRepository _dao_lines;

    @Resource(name = "PoLinesManager")
    private PoLinesManager _manger_lines;

    @Resource(name = "PoLinesMrpLinesManager")
    private PoLinesMrpLinesManager _manger_lines_mrp_lines;

    @Resource(name = "PoLinesMrpFeedingLinesManager")
    private PoLinesMrpFeedingLinesManager _manger_lines_mrp_feeding_lines;

    @Resource(name = "ProductionInstructionLinesRepository")
    private ProductionInstructionLinesRepository _dao_mo_lines;

    @Resource(name = "MrpLinesResultRepository")
    private MrpLinesResultRepository _dao_mrp_lines;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public String fetchNewBillNo() throws Exception {
        return _dao.fetchNewBillNo();
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchByHeaderKey(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        // 得到采购订单表头信息
        _result.put("HeaderEntity", _dao.fetchByKey(MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getLong(criterion, "WorkFlowId")));
        _result.put("PoLinesList", _manger_lines.fetchForPage(criterion));
        _result.put("PoMaterialList", _dao_lines.fetchPoMaterialList(MapUtils.getLong(criterion, "HeaderId")));

        // 得到引入的调达表信息
        criterion.replace("Limit", criterion.get("Limit02"));
        _result.put("LinesMrpList", _dao_lines_mrp.fetchByHeaderId(MapUtils.getLong(criterion, "HeaderId")));
        _result.put("LinesMrpLinesList", _manger_lines_mrp_lines.fetchForPage(criterion));

        // 得到引入的补料单信息
        criterion.replace("Limit", criterion.get("Limit03"));
        _result.put("LinesMrpFeedingList", _dao_lines_mrp_feeding.fetchByHeaderId(MapUtils.getLong(criterion, "HeaderId")));
        _result.put("LinesMrpFeedingLinesList", _manger_lines_mrp_feeding_lines.fetchForPage(criterion));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchPrintPreviewData(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "CurrentUserId"), 0L));
        // 0：无小计行 否则带小计
        if (MapUtils.getInteger(criterion, "GroupMode") == 0) {
            _result.put("poPrintLinesData", _dao_lines.fetchLinesWithOutSubTotal(criterion));   // 导出excel明细 没有小计               
        } else {
            _result.put("poPrintLinesData", _dao_lines.fetchLinesWithSubTotal(criterion));      // 导出excel为全部明细 有小计
        }

        // 打印参数
        _result.put("GroupMode", MapUtils.getString(criterion, "GroupMode"));                  // 有/无 小计 
        _result.put("TotalRows", _dao_lines.fetchForCount(criterion));
        _result.put("PrintRowStart", MapUtils.getInteger(criterion, "PrintRowStart"));
        _result.put("PrintRowEnd", MapUtils.getInteger(criterion, "PrintRowEnd"));
        _result.put("PringPageRows", MapUtils.getString(criterion, "PringPageRows"));
        _result.put("PrintFooter", MapUtils.getString(criterion, "PrintFooter"));
        _result.put("PrintTemplate", MapUtils.getString(criterion, "PrintTemplate"));
        _result.put("ShowTotalQuantity", MapUtils.getString(criterion, "ShowTotalQuantity"));  // 是否显示合计数量

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchExportMemoData(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 订单各款款号
        _result.put("StyleNoList", _dao_lines_mrp_lines.fetchPoStyleNoByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 取得颜色数量
        _result.put("ColourNum", _dao_mo_lines.fetchMaxColourNumFromMoByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 订单各款颜色
        _result.put("ProductColourList", _dao_mo_lines.fetchProductColourFromMoByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 订单各款尺码
        _result.put("ProductSizeList", _dao_mo_lines.fetchProductSizeFromMoByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 订单各款对应的颜色尺码成品数
        _result.put("ProductQuantityList", _dao_mo_lines.fetchProductQuantityFromMoByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 订单各款对应的圆卡使用量
        _result.put("RoundCardQuantity", _dao_mrp_lines.fetchRoundCardQuantityFromMrpByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));
        // 订单各款对应的衣架贴使用量
        _result.put("HangerStickerQuantity", _dao_mrp_lines.fetchHangerStickerQuantityFromMrpByPoHeaderId(MapUtils.getLong(criterion, "PoHeaderId")));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<PoHeaderEntity> itemList = _dao.fetchForPage(criterion);
            Paginator<PoHeaderEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Long insert(PoHeaderEntity instance) throws Exception {
        Long key = _dao.insert(instance);
        if (key != null && key > 0) {
            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "采购管理→采购订单主表", "订单号：" + instance.getPoNo(), "增加");
        }

        return key;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer update(PoHeaderEntity instance) throws Exception {
        Integer rowsAffected = _dao.update(instance);
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "采购管理→采购订单主表", "订单号：" + instance.getPoNo(), "更新");
        }
        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer updatePrintFlag(Long poId) throws Exception {
        return _dao.updatePrintFlag(poId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        // 删除
        Integer rowsAffected = _dao.delete(MapUtils.getLong(criterion, "HeaderId"));
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "采购管理→采购订单主表", "订单号：" + MapUtils.getString(criterion, "DeletedPoNo"),
                    "删除");
        }
        return fetchForPage(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<String> fetchPoNoForAutoComplate(String keyWord) throws Exception {
        return _dao.fetchPoNoForAutoComplate(keyWord);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy, Short isCheckCurrentNode,
            Integer pageIndex, Integer limit) throws Exception {
        _dao.doCheck(headerId, workFlowId, nodeOrder, checkedBy, isCheckCurrentNode);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));
        Map<String, Object> criterion = new HashMap();
        criterion.put("Limit", limit);
        criterion.put("PageIndex", pageIndex);
        criterion.put("HeaderId", headerId);
        _result.put("PoLinesList", _manger_lines.fetchForPage(criterion));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doUnCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy,
            Integer pageIndex, Integer limit) throws Exception {
        _dao.doUnCheck(headerId, nodeOrder, checkedBy);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));
        Map<String, Object> criterion = new HashMap();
        criterion.put("Limit", limit);
        criterion.put("PageIndex", pageIndex);
        criterion.put("HeaderId", headerId);
        _result.put("PoLinesList", _manger_lines.fetchForPage(criterion));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchCheck(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        // 第一步： 审核
        List<Map<String, Object>> _checkedDataList = (List<Map<String, Object>>) criterion.get("CheckData");
        _dao.batchCheck(_checkedDataList);

        // 第二步： 取得当前审核后的数据
        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<PoHeaderEntity> itemList = _dao.fetchForPage(criterion);
            Paginator<PoHeaderEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }
}
